package com.tuo51.components.aliyun.impl;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CopyObjectRequest;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.tuo51.components.aliyun.OSSProcessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Created with teach-system
 * User : Ting.Yao
 * Date : 2014/12/24.
 */
@Service
@Slf4j
@Transactional
public class OSSProcessServiceImpl implements OSSProcessService {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    @Value("${aliyun.oss.bucketPath}")
    private String bucketPath;

    @Override
    public String aliyunOssUpload(String relativePath, MultipartFile file) {
        OSSClient ossClient = new OSSClient(endpoint, (CredentialsProvider)(new DefaultCredentialProvider(accessKeyId, accessKeySecret)), (ClientConfiguration)null);
//        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            if (!ossClient.doesBucketExist(bucketName)) {
                /*
                 * Create a new OSS bucket
                 */
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest= new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }

            ossClient.putObject(new PutObjectRequest(bucketName, relativePath, file.getInputStream()));
            ossClient.setObjectAcl(bucketName, relativePath, CannedAccessControlList.PublicRead);
            ossClient.setObjectAcl(bucketName, relativePath, CannedAccessControlList.Default);

            return relativePath;
        } catch (OSSException oe) {
            oe.printStackTrace();
        } catch (ClientException ce) {
            ce.printStackTrace();
        } catch (IOException ie){
            ie.printStackTrace();
        } finally{
            ossClient.shutdown();
        }

        return null;
    }




    @Override
    public String aliyunOssUpload1(String relativePath, MultipartFile file) {
        try {
            // 创建OSSClient2.8.3实例
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            //上传文件流
            InputStream inputStream = file.getInputStream();
//            String filename = file.getOriginalFilename();

            //添加一个UUID值
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //拼接到filename前面
            String filename =uuid+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            //2019/11/17/01.jpg
            //获取当前日期，转换/2019/11/17
//            SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy/MM/dd");
//            String timeUrl = simpleDateFormat.format(new Date());
//            filename =timeUrl+"/"+filename;

            try {
                ossClient.putObject(bucketName, filename, inputStream);
                log.info("阿里云上传文件成功，bucketName:{},key:{},url:{}", bucketName, accessKeyId, bucketPath);
            }catch(Exception e) {
                log.warn("阿里云上传文件失败：{},bucketName:{},key:{}", e.getMessage(), bucketName, accessKeyId);
                throw new Exception("阿里云上传文件失败");
            }finally {
                ossClient.shutdown();
            }
            //返回上传之后url地址--例如： https://guli-edu-191117.oss-cn-beijing.aliyuncs.com/7.jpg
//            String url = "https://" + bucketPath + "/" + filename;
            return filename;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }




    @Override
    public String aliyunOssUpload(String relativePath, File file) {
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            if (!ossClient.doesBucketExist(bucketName)) {
                /*
                 * Create a new OSS bucket
                 */
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest= new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }

            ossClient.putObject(new PutObjectRequest(bucketName, relativePath, file));
            ossClient.setObjectAcl(bucketName, relativePath, CannedAccessControlList.PublicRead);
            ossClient.setObjectAcl(bucketName, relativePath, CannedAccessControlList.Default);

        } catch (OSSException oe) {

        } catch (ClientException ce) {

        }finally{
            ossClient.shutdown();
        }
        return relativePath;
    }

    @Override
    public void aliyunOssDelete(String relativePath) {
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        ossClient.deleteObject(bucketName, relativePath);
    }

    @Override
    public void aliyunOssCopy() {
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        CopyObjectRequest copyObjectRequest = new CopyObjectRequest("", "", "", "");
    }
}
